package com.bahehe.hsinchubus;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


import com.bahehe.hsinchubus.db.dbMyFavor;
import com.bahehe.widget.CustomListView;
import com.bahehe.widget.CustomListView.OnRefreshListener;
import com.kuad.KuBanner;








import android.R.integer;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;

import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;



public class MyFavor extends ActivityGroup {

	private static final String TAG="MyFavor";
	private static final String DATABASE_NAME = "hsinchubus.db";	//資料庫名稱
	private static final int DATABASE_VERSION = 1;	//資料庫版本
	private static final String TABLE_NAME = "myfavor";
	private dbMyFavor dbHelper;

	
	private final static String URL_GET_BUSSTOP_TIME = "http://hisatisfy.hccg.gov.tw/HSbus/Map/time/ws/getRunPredictionTime.aspx?hash=20440715090265615&run_id=";
	
	//private ArrayList<String> arFavorGroups = new ArrayList<String>();
	public static ArrayList<HashMap<Integer, Object>> MyFavorGroups = new ArrayList<HashMap<Integer, Object>>();
	
	private CustomListView mListMyFavor;
	private ArrayList<HashMap<String, Object>> myfavorList = null;
	private ArrayList<SearchResultsFavor> searchResults = null;
	private CustomBaseAdapter1 myfavorAdapter;
	private ArrayList<String> saveBusStopName = new ArrayList<String>();
	private ArrayList<String> saveBusTime = new ArrayList<String>();
	private ArrayList<String> saveFavorBusTime = new ArrayList<String>();
	private ArrayList<SearchResultsFavor> mFavorresults  = null;
	
	private static String selBusBusStop;
	private static String selBusRouteName;
	
	private static int sel_idx = -1;
	
	private static HashMap<Integer, Object> delFavorData = null;
	
	private static boolean isRead = false;

	final Handler mHandler = new Handler();
	  private Runnable mUpdateData = new Runnable()
	  {
	    public void run()
	    {
	    	MyFavor.this.UpData();
	    	MyFavor.this.mHandler.postDelayed(this, 30000L);
	    }
	  };
	  final Runnable mUpdateView = new Runnable()
	  {
	    public void run()
	    {
	    	//MyFavor.this.Up
	    }
	  };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		  requestWindowFeature(Window.FEATURE_NO_TITLE);  
	        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
	                WindowManager.LayoutParams.FLAG_FULLSCREEN);  
	        setContentView(R.layout.myfavor);	        
	        if(dbHelper == null)
	        	dbHelper = new dbMyFavor(this,DATABASE_NAME,null,DATABASE_VERSION);
	        
	        mListMyFavor = (CustomListView)findViewById(R.id.lstMyFavor);
	        
	        mListMyFavor.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	        
	        mListMyFavor.setOnCreateContextMenuListener(RemoveFavorClickListener);
	        //mListMyFavor.setOnItemLongClickListener(BusTimeLongClickListener);
	        //mListMyFavor.setOnItemClickListener(BusTimeClickListener);
	        //mListMyFavor.setOnItemSelectedListener(BusTimeSelectedListener);
	     //   Log.i(TAG,"onCreate()");
	        
	        KuBanner banner = (KuBanner)findViewById(R.id.kuadview);
	        banner.setAPID("000000d7m");
	        
	        mListMyFavor.setonRefreshListener(new OnRefreshListener() {  
	            public void onRefresh() {  
	                new Thread(new Runnable() {  
	                    public void run() {  
	                    	
	                        try {
	                        		//GetDataFromDB();
	                        	    MyFavor.this.mHandler.postDelayed(MyFavor.this.mUpdateData, 0L);
		                            Thread.sleep(3000); 
		                             //GetData();
		                            
		                        } catch (Exception e) {  
	                        }  
	  
	                        runOnUiThread(new Runnable() {  
	                            public void run() {  
	                            	mListMyFavor.onRefreshComplete();  
	                            }  
	                        });  
	                    }  
	                }).start();  
	            }  
	        });  
	        
	
	       
	        //this.myfavorAdapter = new CustomBaseAdapter1(this,null);
	        GetData();
	}
	
	
	
     private OnCreateContextMenuListener RemoveFavorClickListener= new OnCreateContextMenuListener() {  
         
         @Override  
         public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
             menu.setHeaderTitle("常用路線管理");     
             menu.add(0, 0, 0, "移除此筆紀錄");  
         }
    
         
     };
     

 	
 	
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    int index = info.position;
	//    Log.i(TAG,"Sel Menu 1= " + index);
	    
	    
		if(item.getItemId() == 0){
		
		sel_idx = MyFavor.this.myfavorAdapter.selected;
		Log.i(TAG,"MyPos 1= " + sel_idx);
		if(sel_idx>0 &&MyFavorGroups.size() > 0){

            HashMap<Integer, Object> hmData  = MyFavorGroups.get(sel_idx-1);        

			selBusBusStop = hmData.get(Integer.valueOf(1)).toString() ;
			selBusRouteName= hmData.get(Integer.valueOf(4)).toString();

			deleteStop(selBusBusStop,selBusRouteName) ;
			this.mListMyFavor.setAdapter(this.myfavorAdapter);
		    this.mListMyFavor.setOnItemLongClickListener(this.myfavorAdapter);
		    this.myfavorAdapter.selected = -1;
		    //UpData();
		    myfavorAdapter.notifyDataSetChanged();
			this.mHandler.postDelayed(this.mUpdateData, 0L);
		}
		
		 
		}

		return super.onContextItemSelected(item);
	}
	
	private void deleteStop(String selBusStop, String BusRouteName){
		
		Log.i(TAG,"deleteStop()");
		int flag = -1;
			if(sel_idx == -1)
				return;
		
			if(MyFavorGroups.size()>0){
				
				MyFavorGroups.remove(sel_idx-1);
				SQLiteDatabase  db = this.dbHelper.getWritableDatabase();				
				String strSQL ="delete from MyFavor where "+
		                 "busstop= \""+selBusStop + 
		                  "\" and route_name= \"" + BusRouteName +"\"";
				Log.i(TAG,strSQL);
		 	//	int ret1 = -1;
				System.out.println(MyFavorGroups);
		 		
		 		try {		 			  
		 			 db.execSQL(strSQL);		 			 
		 		}catch (Exception e) {
		 			 flag = 0;
		             Toast.makeText(MyFavor.this, "刪除失敗!", Toast.LENGTH_SHORT).show();
					// TODO: handle exception
				}finally{
					if(db!=null)
					  db.close();
					
					if( flag ==-1){ 						
						Toast.makeText(MyFavor.this, "刪除成功!", Toast.LENGTH_SHORT).show();		
						
					}
					
				}
			}
			
	//	}
   
		
 		
 		//return ret;
		
	}

	private void GetData(){
	    GetDataFromDB();
        
        try {
        	searchResults = GetSearchResults();
        	if(searchResults!=null){
            	myfavorAdapter = new CustomBaseAdapter1(MyFavor.this, searchResults);
            	mListMyFavor.setOnItemLongClickListener(myfavorAdapter);
     	        mListMyFavor.setAdapter(myfavorAdapter); 
        	}
        
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	private void GetSearchResults(String BusStop, String BusTime){
		
	     //ArrayList<SearchResultsFavor> results = new ArrayList<SearchResultsFavor>();
	   //  Log.i(TAG,"GetSearchResults()");
		
		 if(MyFavorGroups!=null && MyFavorGroups.size() == 0)
		     mFavorresults.clear();
		 
	     if(MyFavorGroups!=null && MyFavorGroups.size() > 0){		     
			     for(int i=0;i<MyFavorGroups.size() ; i++){
			    	 if(MyFavorGroups.get(i).get(Integer.valueOf(1)).toString().equals(BusStop)){
			    		 SearchResultsFavor sr = new SearchResultsFavor();
			    		 sr.setBusstop(MyFavorGroups.get(i).get(Integer.valueOf(1)).toString());
				    	 sr.setRoute_name(MyFavorGroups.get(i).get(Integer.valueOf(4)).toString());
					     sr.setBustime(BusTime);
				    	 //sr.setBustime("更新中");
					     mFavorresults.add(sr);
			    	 }
			    	
			     }			   
			    
			   
	     }
    }
	
	private ArrayList<SearchResultsFavor> GetSearchResults(){
		
	     ArrayList<SearchResultsFavor> results = new ArrayList<SearchResultsFavor>();
	 //    Log.i(TAG,"GetSearchResults()");
	     if(MyFavorGroups!=null && MyFavorGroups.size() > 0){
			     //Iterator<HashMap<Integer, Object>> iterator = MyFavorGroups.iterator();
		//	     System.out.println(MyFavorGroups);
			     
			     for(int i=0;i<MyFavorGroups.size() ; i++){
			    	 SearchResultsFavor sr = new SearchResultsFavor();
			    	 sr.setBusstop(MyFavorGroups.get(i).get(Integer.valueOf(1)).toString());
			    	 sr.setRoute_name(MyFavorGroups.get(i).get(Integer.valueOf(4)).toString());
				     sr.setBustime("更新中");
				     results.add(sr);
			     }			   
			//     System.out.println("123");
			//     System.out.println(results);
			     return results;
	     }else {
	    	 return null;
		}     
   }
	
	private void GetDataFromDB(){

		Log.i(TAG,"GetDataFromDB()");
 		SQLiteDatabase  db = this.dbHelper.getReadableDatabase();
 		Cursor cursor = null;
 		try {
 	 		cursor = db.query(MyFavor.TABLE_NAME, new String[] {
 	                "groups","busstop","route_id","route_number","route_name"
 	        }, null, null, null, null,null);
 	 		
 	 		
 	 		if(MyFavorGroups!=null &&MyFavorGroups.size()>0){
 	 			MyFavorGroups.clear();
 	 		}
 	 		while (cursor.moveToNext()) {
	 	 		HashMap<Integer, Object> hmData = new HashMap<Integer, Object>();
	 	 		hmData.put(Integer.valueOf(0), cursor.getString(0));
	 	 		hmData.put(Integer.valueOf(1), cursor.getString(1));
	 	 		hmData.put(Integer.valueOf(2), cursor.getString(2));
	 	 		hmData.put(Integer.valueOf(3), cursor.getString(3));
	 	 		hmData.put(Integer.valueOf(4), cursor.getString(4));
	 	 		MyFavorGroups.add(hmData);
 	 		}
		} catch (Exception e) {
			Log.e(TAG,"Error->"+e.getMessage());
		}finally{			
			if(cursor!=null)
				cursor.close();
			if(db!=null)
				db.close();
		}
 }
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		this.mHandler.removeCallbacks(this.mUpdateData);
		Log.i(TAG,"MyFavor onPause() ");
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		GetData();
		Log.i(TAG,"MyFavor onResume() ");
		this.mHandler.postDelayed(this.mUpdateData, 0L);
		super.onResume();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		Log.i(TAG,"MyFavor onStop() ");
		super.onStop();
	}
	
 	 		

	private void UpData()
	{
//		GetData();
		 if(saveBusStopName!=null && saveBusStopName.size()>0){
		    	saveBusStopName.clear();
		    	saveBusTime.clear();
		    	saveFavorBusTime.clear();
	    }
		 mFavorresults = new ArrayList<SearchResultsFavor>();
	    Iterator Iterator = MyFavorGroups.iterator();
	    while (Iterator.hasNext())
	    {	   
	      UpData((HashMap<Integer, Object>)Iterator.next());
	    }
	  }

	  private void UpData(HashMap<Integer, Object> hm){
	  
	    new myFavorRequest(
	    		hm.get(Integer.valueOf(1)).toString(),
	    		hm.get(Integer.valueOf(2)).toString()
	    		).execute(new Void[0]);
	   // this.mHandler.post(this.mUpdateView);
	
	  }
	  
	  private class myFavorRequest extends HttpAsync {
		  
		  private String strBusStop;
		  
		  public myFavorRequest(String strBusStop, String strRouteID){		  
		      super(URL_GET_BUSSTOP_TIME+strRouteID);
		      this.strBusStop = strBusStop;
		  }
		  
		  public void GetBusTime(String paramString){
			  Log.i(TAG,paramString);
		  
			  int idx_0 = paramString.indexOf(strBusStop);
			  String NewString0  = paramString.substring(idx_0-40, idx_0).toString();
		//	  Log.i(TAG,NewString0);
			  
			  int idx_1=NewString0.indexOf("\"time\":");
			  int idx_2=NewString0.indexOf("\"idx\":");
			  
			  String strBusStopTime = NewString0.substring(idx_1 + 8, idx_2-2);
		//	  Log.i(TAG,strBusStopTime);  
			  //saveFavorBusTime.add(strBusStopTime);
			  GetSearchResults(strBusStop, strBusStopTime);
		  }
		  
		  public void updateview(){
			  
			  Log.i(TAG,"updateview()");
			   // TextView aa = (TextView)findViewById(R.id.txtTitle);
			  	//if(saveFavorBusTime!=null &&saveFavorBusTime.size()>0){
			  		try {
			        	searchResults = mFavorresults;
			        	if(searchResults!=null){
			        		for(int i=0 ;i<searchResults.size();i++){
			        		//	aa.setText(searchResults.get(i).getBustime().toString());
				        		Log.i(TAG,"searchResults 1 =" + searchResults.get(i).getBustime().toString());
				             	Log.i(TAG,"searchResults 2 =" + searchResults.get(i).getBusstop().toString());
				        		Log.i(TAG,"searchResults 3 =" + searchResults.get(i).getRoute_name().toString());
				        	}	
			        		if(MyFavorGroups.size()==0)
			        			searchResults.clear();
			        		Log.i(TAG,"searchResults = "+searchResults);
			        	   myfavorAdapter = new CustomBaseAdapter1(MyFavor.this, searchResults);				         
				 	       mListMyFavor.setAdapter(myfavorAdapter);
				 	       mListMyFavor.setOnItemLongClickListener(myfavorAdapter);
				 	       myfavorAdapter.notifyDataSetChanged();
			        	}
//		        	}	
					} catch (Exception e) {
						// TODO: handle exception
					}
			 // 	}
			  		
			
		  }
		  
	  }
	  
	  
	 
	public abstract class HttpAsync extends AsyncTask<Void, Void, Void>{
		
		private String requestStr;
		private boolean bAsync = true;
		
		public HttpAsync(){
			
		}
		
		public HttpAsync(String paramString){
		
		    this.requestStr = paramString;
		    Log.i(TAG,requestStr);
		}
		
		public void SetRequestStr(String paramString)	{
		    this.requestStr = paramString;
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			HttpGet hg = new HttpGet(this.requestStr);
			try {
				HttpResponse hr = new DefaultHttpClient().execute(hg);
		        if(hr.getStatusLine().getStatusCode()==200){
		        	if(bAsync){
		        	  	String strResult = EntityUtils.toString(hr.getEntity());
			        	GetBusTime(strResult);
		        	}
		      
		        	//Log.i(TAG,strResult);
		        }
			} catch (Exception e) {
				// TODO: handle exception
			}
			
			return null;
		}
		public abstract void GetBusTime(String paramString);
		public abstract void updateview();
		

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			   if (this.bAsync){
				   Log.i(TAG,"Http updateview()");
				   updateview();
			   }
				     
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
		
		public void Stop(){
	  
			Log.i("MayFavor","Stop()");
		    this.bAsync = false;
		    super.cancel(true);
		 }
		
		
	}

}


